<template>
    <div class="-mt-4px">
        <el-upload ref="uploadRef" action="#" :accept="accept" :auto-upload="false" :limit="1"
                   :on-change="onChange">
            <el-button type="primary" size="small">上传</el-button>
        </el-upload>
        <div v-if="fullBase64" class="mt-6px">
            <BigPicture text="点击查看" :imageUrl="fullBase64" />
        </div>
    </div>
</template>
<script lang="ts" setup>
import {ref, watch} from 'vue'
import {ElMessage} from 'element-plus'
import type {UploadFile, UploadRawFile} from 'element-plus'
import BigPicture from '@/components/bigPicture/index.vue'

const props = defineProps({
    imageUrl: {
        type: String,
        default: ''
    }
})

const accept = ['.png', '.jpg', '.jpeg', '.bmp']

const uploadRef = ref()

const emits = defineEmits(['update:imageUrl'])

const fullBase64 = ref('')


watch(()=>props.imageUrl, (newval) => {
    console.log(1234, newval)
    if(newval?.startsWith('https')) {
        fullBase64.value = newval
    }
}, {
    immediate: true
})

const fileToBase64 = (file: UploadRawFile) => {
    return new Promise<string>((resolve) => {
        const reader = new FileReader()
        reader.onload = (evt) => {
            console.log(999, evt)
            if (evt?.target?.result) {
                const result = (evt.target.result as string).split('base64,')[1]
                resolve(result)
            }

        }
        reader.readAsDataURL(file)
    })
}

const onChange = async (file: UploadFile) => {
    if (accept.some(i => file.name.endsWith(i))) {
        const base64 = await fileToBase64(file.raw as UploadRawFile)
        emits('update:imageUrl', base64)
    } else {
        ElMessage.error('请上传正确格式的文件')
        uploadRef.value?.clearFiles()
    }
}

const clearFiles = () => {
    uploadRef.value?.clearFiles()
}

defineExpose({clearFiles})

</script>
<style lang="scss" scoped></style>